//
//  CZComposeViewController.swift
//  weibo
//
//  Created by Apple on 16/3/18.
//  Copyright © 2016年 KY. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking
class CZComposeViewController: UIViewController {
    //  标记是否执行toolBar动画
    var isToolBarAnimation: Bool = true
    // MARK:   懒加载控件
    private lazy var sendButton: UIButton = {
        let button = UIButton()
        button.addTarget(self, action: "sendButtonAction", forControlEvents: .TouchUpInside)
        //  设置按钮的三种状态
        button.setBackgroundImage(UIImage(named: "common_button_orange"), forState: .Normal)
        button.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: .Highlighted)
        button.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: .Disabled)
        button.setTitle("发送", forState: .Normal)
        //  设置不可用状态颜色
        button.setTitleColor(UIColor.darkGrayColor(), forState: .Disabled)
        //  设置默认状态的颜色
        button.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        //  设置文字大小
        button.titleLabel?.font = UIFont.systemFontOfSize(15)
        button.size = CGSize(width: 45, height: 35)
        return button
    }()
    
    private lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.textAlignment = .Center
        label.font = UIFont.systemFontOfSize(16)
        if let name =  CZUserAccountViewModel.sharedAccount.userAccount?.screen_name {
            //  多行显示
            label.numberOfLines = 0
            let title = "发微博\n" + name
            //  方式1
//            let attributedStr: NSMutableAttributedString = NSMutableAttributedString(string: title)
//           
//            attributedStr.addAttributes([NSFontAttributeName: UIFont.systemFontOfSize(14)], range: NSMakeRange(3, title.characters.count-3))
            //  方式2
            let attributedStr: NSMutableAttributedString = NSMutableAttributedString(string: title)
            let nameRange = (title as NSString).rangeOfString(name)
            attributedStr.addAttributes([NSFontAttributeName: UIFont.systemFontOfSize(12), NSForegroundColorAttributeName: UIColor.lightGrayColor()], range: nameRange)
            label.attributedText = attributedStr
        } else {
            label.text = "发微博"
        }
        label.sizeToFit()
        return label
    }()
    
    private lazy var textView: CZTextView =  {
        //  1.使用代码创建
//        let textView = CZTextView()
//        textView.font = UIFont.systemFontOfSize(14)
//        textView.placeholder = "听说下雨天音乐跟辣条更配哟~"
//        return textView
        //  2.使用xib加载
        let textView = UINib(nibName: "CZTextView", bundle: nil).instantiateWithOwner(nil, options: nil).last! as! CZTextView
        textView.placeholder = "听说下雨天音乐跟辣条更配哟~"
        textView.font = UIFont.systemFontOfSize(14)
        textView.delegate = self
        //  设置可以滚动的效果
        textView.alwaysBounceVertical = true

        return textView
    }()
    
    private lazy var toolBar: CZComposeToolBar = CZComposeToolBar(frame: CGRectZero)
    
    private lazy var emoticonKeyBoard: CZEmoticonKeyBoard = {
        let view = CZEmoticonKeyBoard(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: ScreenWidth, height: 200)))

        return view
    }()
    
    //  图片显示的视图
    private lazy var pictureView: CZComposePictureView = {
        let view = CZComposePictureView()
        //  防止循环引用
        view.addImageClosure = { [weak self] in
            self?.pictureSelected()
        }
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        //   注册通知，监听插入表情事件
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "emoticonSelect:", name: CZEmoticonNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "deleteEmoticonAction", name: CZDeleteEmoticonNotification, object: nil)
    }
    
    private func setNavUI() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: "leftAction")
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: sendButton)
        //  默认进来就是不可用的状态,顺序不能不能变，先添加自定义按钮，然后设置不可用的状态
        navigationItem.rightBarButtonItem?.enabled = false
        //  设置titleview
        navigationItem.titleView = titleLabel
    }

    private func setupUI() {
        view.backgroundColor = UIColor(white: 0.95, alpha: 1)
        setNavUI()
        
        //  添加控件
        view.addSubview(textView)
        view.addSubview(toolBar)
        textView.addSubview(pictureView)
        //  添加约束
        textView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(UIEdgeInsetsZero)
        }
        toolBar.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(self.view)
            make.bottom.equalTo(self.view)
            make.trailing.equalTo(self.view)
            make.height.equalTo(44)
        }
        
        pictureView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(textView)
            make.width.equalTo(textView).offset(-20)
            make.height.equalTo(textView.snp_width).offset(-20)
            make.top.equalTo(textView).offset(100)
        }
        //  设置闭包 ,闭包循环引用了，如果使用self，则使用[weak self]
        toolBar.composeButtonClickClosure = { [weak self] (type: CZComposeToolBarType)->() in
            switch type {
            case .Picture:
                self?.pictureSelected()
            case .Mention:
                print("Mention")
            case .Trend:
                print("Trend")
            case .Emotion:
                self?.switchEmotionKeyBoard()
            case .Add:
                print("Add")
                
            }
        }
      
        //  注册通知监听键盘弹起和消失
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardDidChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
    }

    
    // MARK:    点击事件
    @objc private func leftAction() {
        //  键盘隐藏
        self.view.endEditing(true)
        dismissViewControllerAnimated(true, completion: nil)
    }
    @objc private func sendButtonAction() {
        //  上传图片
        if pictureView.images.count > 0 {
            upload()
            
        } else {
            update()
        }
        
    }
    
    //  发送图片和文本
    private func upload() {
        let img = self.pictureView.images.first!
        SVProgressHUD.show()
        CZNetWorkTools.netWorkTools.upload(textView.emotionText, accessToken: CZUserAccountViewModel.sharedAccount.accessToken!, img: img) { (response, error) -> () in
            if error != nil {
                SVProgressHUD.showErrorWithStatus("网络异常")
                return
            }
            SVProgressHUD.showSuccessWithStatus("发送成功")
        }
//        let url = "https://upload.api.weibo.com/2/statuses/upload.json"
//        let param = [
//            "status": textView.text!,
//            "access_token": CZUserAccountViewModel.sharedAccount.accessToken!
//        ]
//        SVProgressHUD.show()
//        AFHTTPSessionManager().POST(url, parameters: param, constructingBodyWithBlock: { (formData) -> Void in
//            
//            let img = self.pictureView.images.first!
//            //  高质量的发送，data数据太大
//            //let data = UIImagePNGRepresentation(img)!
//            //  传入质量系数去发送图片
//            let data = UIImageJPEGRepresentation(img, 0.7)!
//            //1.上传的二进制，2，服务器对应接口参数3,filename 服务使用生成的名字，一般随便传，服务端一般不会使用，他们自己会处理，mimeType:如果类型不确定可以使用application/octet-stream
//            
//            formData.appendPartWithFileData(data, name: "pic", fileName: "", mimeType: "image/jpeg")
//            
//            }, progress: nil, success: { (dataTask, response) -> Void in
//                SVProgressHUD.showSuccessWithStatus("发送成功")
//                
//            }, failure: { (dataTask, error) -> Void in
//                SVProgressHUD.showSuccessWithStatus("发送失败")
//        })
    }
    
    //  发送文本
    private func update() {
        
       
//        print(textView.attributedText)
        //  已经抽取到CZTextView分类里面
//        textView.emotionText
        
        CZNetWorkTools.netWorkTools.update(textView.emotionText, accessToken: CZUserAccountViewModel.sharedAccount.accessToken!) { (response, error) -> () in
            if error != nil {
                SVProgressHUD.showErrorWithStatus("网络异常")
                return
            }
            SVProgressHUD.showSuccessWithStatus("发送成功")
        }
    }
    
    @objc private func keyboardDidChangeFrame(noti: NSNotification) {
        //  如果isToolBarAnimation等于false 不执行动画
//        if !isToolBarAnimation {
//            return
//        }
        print(noti.userInfo)
        let keyboardRect = (noti.userInfo?[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        
        toolBar.snp_updateConstraints { (make) -> Void in
            //  如果想要toolbar底部约束设置到键盘的顶部，根据键盘的y值-当前屏幕的高度计算差值
            make.bottom.equalTo(self.view).offset(keyboardRect.origin.y - self.view.height)
        }
        
        UIView.animateWithDuration(0.25) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    //  点击表情按钮
    @objc private func emoticonSelect(noti: NSNotification) {
        let emoticon = noti.object as! CZEmoticon
        //  插入图片表情或者emoji
        textView.insertEmotionText(emoticon)
        
        //  保存最近使用的表情
        CZEmoticonTools.shareEmoticonTools.saveRecentEmoticon(emoticon)
    }
    //  点击表情视图的删除按钮出发的事件
    @objc private func deleteEmoticonAction() {
        textView.deleteBackward()
    }

    deinit {
        //  移除通知
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
}

//  拖动隐藏键盘
extension CZComposeViewController {
    func scrollViewDidScroll(scrollView: UIScrollView) {
        //  滚动让其键盘隐藏
        textView.resignFirstResponder()
    }
}

//  toolbar 点击逻辑
extension CZComposeViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    private func pictureSelected() {
        let imagePickerVC = UIImagePickerController()
        
        //  判断设备是否可以用
        if UIImagePickerController.isSourceTypeAvailable(.Camera) {
            imagePickerVC.sourceType = .Camera
        } else {
            imagePickerVC.sourceType = .PhotoLibrary
        }
        //  判断摄像头是否可以使用,后置摄像头
        if !UIImagePickerController.isCameraDeviceAvailable(.Rear) {
            print("摄像头不可使用")
        }
        //  开启编辑模式
        //imagePickerVC.allowsEditing = true
        imagePickerVC.delegate = self
        
        presentViewController(imagePickerVC, animated: true, completion: nil)
    }
    
    private func switchEmotionKeyBoard() {

        //  1.取消第一响应者
        //  不执行toolbar动画
        //isToolBarAnimation = false
        //textView.resignFirstResponder()
        
    
        //  2.判断是否是系统键盘，如果是系统键盘设置inputview，否则inputview设置为nil
//        if textView.inputView == nil {
//            textView.inputView = view
//        } else {
//            textView.inputView = nil
//        }
        textView.inputView = textView.inputView == nil ? emoticonKeyBoard : nil
        //  如果inputView等于nil则显示表情图片，否则显示键盘图片
        toolBar.isEmotionKeyBoard = (textView.inputView == nil)
        //  执行toolbar动画
        //isToolBarAnimation = true
        textView.becomeFirstResponder()
        //  更新inputview视图
        textView.reloadInputViews()
    }
    
    // MARK:    UIImagePickerController代理方法
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        let img = UIImage.scaleWithWidth(image, width: 300)
        
        pictureView.addImage(img)
        //  取消图片选择控制器
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
  
    
}

extension CZComposeViewController: UITextViewDelegate {
    //  通过代理监听文字改变判断发送按钮是否可以显示可用
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
}
